#include "StdAfx.h"
#include "AbstractBuffer.h"



AbstractBuffer::AbstractBuffer()
{

	boost::shared_ptr<StreamPage>elementPage(new StreamPage);
	this->pageVector.push_back(elementPage);
	this->pageNumber = 1;
	MemoryPosition prevMemoryPosition;

	for(int j = CHUNK_NUMBER_ONE_PAGE-1 ;j>=0; j--)
	{
		this->pageVector[0]->setNextFreePosition(j,prevMemoryPosition);
		prevMemoryPosition.pageIndex = 0;
		prevMemoryPosition.chunkIndex = j;

	}

}
bool AbstractBuffer::allocateNewPage(void)
{
	if(this->pageNumber == MAX_PAGE_NUMBER_IN_ONE_QUEUE_OR_SYNOPSIS)
	{
		return false;
	}
	boost::shared_ptr<StreamPage>elementPage(new StreamPage);
	this->pageVector.push_back(elementPage);
	this->pageNumber++;
	
	MemoryPosition prevMemoryPosition;
	for(int j = CHUNK_NUMBER_ONE_PAGE-1 ;j>=0; j--)
	{
		this->pageVector[pageNumber-1]->setNextFreePosition(j,prevMemoryPosition);
		prevMemoryPosition.pageIndex = pageNumber-1;
		prevMemoryPosition.chunkIndex = j;
	}

	MemoryPosition newMemoryPosition;
	newMemoryPosition.pageIndex = this->pageNumber-1;
	newMemoryPosition.chunkIndex = 0;
	this->pageVector[pageNumber-2]->setNextFreePosition(CHUNK_NUMBER_ONE_PAGE-1,newMemoryPosition);
	
	return true;
}


AbstractBuffer::~AbstractBuffer(void)
{
}
bool AbstractBuffer::isValidMemoryPosition(MemoryPosition& memoryPosition)
{
	
	return memoryPosition.pageIndex>=0&&memoryPosition.pageIndex<=this->pageNumber-1
		&& memoryPosition.chunkIndex>=0&&memoryPosition.chunkIndex<=CHUNK_NUMBER_ONE_PAGE-1;
}
void AbstractBuffer::getElementByMemoryPosition(Element&element,MemoryPosition& memoryPosition)
{
	assert(isValidMemoryPosition(memoryPosition));
	this->pageVector[memoryPosition.pageIndex]->getValue(memoryPosition.chunkIndex,element);

}
void AbstractBuffer::setElementByMemoryPosition(Element&element,MemoryPosition& memoryPosition)
{
	assert(isValidMemoryPosition(memoryPosition));
	this->pageVector[memoryPosition.pageIndex]->setValue(memoryPosition.chunkIndex,element);
}
//boost::shared_ptr<StreamPage>& AbstractBuffer::getPageByIndex(int i )
//{
//	return this->pageVector[i];
//}
void AbstractBuffer::setNextPosition(MemoryPosition& chunkMemoryPosition, MemoryPosition& nextFreeHeadPointerPosition)
{
	this->pageVector[chunkMemoryPosition.pageIndex]->setNextFreePosition(chunkMemoryPosition.chunkIndex,nextFreeHeadPointerPosition);
}
void AbstractBuffer::getNextPosition(MemoryPosition& chunkMemoryPosition, MemoryPosition& nextFreeHeadPointerPosition)
{
	this->pageVector[chunkMemoryPosition.pageIndex]->getNextFreePosition(chunkMemoryPosition.chunkIndex,nextFreeHeadPointerPosition);
}
int AbstractBuffer::getPageNumber(void)
{
	return this->pageNumber;
}